/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.floor.web.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.commodity.enums.GoodsStatusEnum;
import com.wealth.commodity.service.ICategoryService;
import com.wealth.commodity.service.IGoodsService;
import com.wealth.commodity.vo.CategoryVO;
import com.wealth.commodity.vo.FloorGoodsVO;
import com.wealth.floor.entity.PcFloor;
import com.wealth.floor.entity.PcFloorItem;
import com.wealth.floor.service.IPcFloorItemService;
import com.wealth.floor.service.IPcFloorService;
import com.wealth.floor.service.PcFloorService;
import com.wealth.system.entity.User;
import com.wealth.system.service.ShiroUser;
import com.wealth.system.web.controller.BaseController;

import iaas.enums.StatusEnum;
import iaas.utils.RedirectMessage;
import iaas.utils.ResultObject;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;
import net.sf.json.JSONObject;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Controller
@RequestMapping(value="/manage/floor/pcFloor")
public class PcFloorController extends BaseController{

	Logger logger = Logger.getLogger(PcFloorController.class);
	
	@Autowired
	private IPcFloorService pcFloorService;
	
	@Autowired
	private ICategoryService categoryService;
	@Autowired
	private PcFloorService floorService;
	@Autowired
	private IGoodsService goodsService;
	@Autowired
	private IPcFloorItemService floorItemService;
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	/*@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		try{
			if (id != -1) {
				PcFloor pcFloor = pcFloorService.get(id);
				model.addAttribute("pcFloor", pcFloor);
			}
		}catch(Exception e){
			logger.error("初始化错误", e);
		}
	}*/
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(Model model){
		Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
		model.addAttribute("corpid", corpid);
		return "floor/pcFloor/list";
	}
	
	
	/**
	 * 列表ajax查询数据
	 */
	@RequestMapping(value="/list",method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model,JqGridRequest request) {
		try{

			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			
			Page<PcFloor> page = pcFloorService.get(corpid, request,PcFloor.class);
			
			return JqGridUtil.getJqGrirdResponse(page);
		}catch(Exception e){
			logger.error("列表错误！", e);
			return null;
		}
	}
	/**楼层详情*/
	@RequestMapping(value="/floorInfo/{id}")
	@ResponseBody
	public JqGridResponse getfloorInfo(Model model,JqGridRequest request,@PathVariable Long id){
		try{
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			Page<PcFloorItem> page = floorItemService.get(corpid, request,PcFloorItem.class,id);
			return JqGridUtil.getJqGrirdResponse(page);
		}catch(Exception e){
			logger.error("列表错误！", e);
			return null;
		}
	}
	/**
	 * 详情
	 */
	@RequestMapping(value="/{id}",method = RequestMethod.GET)
	public String infoForm(Model model,@PathVariable("id") Long id){
		try{
			PcFloor pcFloor = pcFloorService.get(id);
			model.addAttribute("pcFloor", pcFloor);
			return "floor/pcFloor/info";
		}catch(Exception e){
			logger.error("详情页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	
	/**
	 * 创建页面
	 */
	@RequestMapping(value="/create",method = RequestMethod.GET)
	public String createForm(Model model){
		try {
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			List<CategoryVO> voList = categoryService.getCategoryByStatusAndCorpId(StatusEnum.NORMAL.getValue(), corpid);
			model.addAttribute("voList", voList);
			Map<String,Object> map = new  HashMap<String, Object>();
			String floorUrl1 = floorService.getFloorUrl();
			model.addAttribute("floorUrl1", floorUrl1);
			/**把所有的分类转成json字符串*/
			map.put("volist", voList);
			JSONObject.fromObject(map).toString();
			model.addAttribute("voListJson", JSONObject.fromObject(map).toString());
			/**查询所有的商品*/
			Map<String,Object> goodsmap = new  HashMap<String, Object>();
			List<FloorGoodsVO> goodsList = goodsService.getGoodsAllForFloor(GoodsStatusEnum.UP.getValue());
			goodsmap.put("goodsList", goodsList);
			JSONObject.fromObject(goodsmap).toString();
			model.addAttribute("goodsList",goodsList);
			model.addAttribute("goodsvoList", JSONObject.fromObject(goodsmap).toString());
			return "floor/pcFloor/create";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 创建
	 */
	@RequestMapping(value="/create",method = RequestMethod.POST)
	public String create(Model model,PcFloor entity,RedirectAttributes redirectAttributes){
		try {
			User user = ShiroUser.getInstance().getUser();
			entity.setCorp(user.getCorp());
			entity.setStatus(StatusEnum.NORMAL.getValue());
			entity.setCreator(user.getUsername());
			entity.setCreateTime(new Date());
			pcFloorService.save(entity);
			List<PcFloorItem> itemList = entity.getPcfloorList();
			if(itemList.size()>0){
				for (PcFloorItem item : itemList) {
					item.setCreateTime(new Date());
					item.setCreator(user.getUsername());
					item.setFloor(entity);
					item.setStatus(StatusEnum.NORMAL.getValue());
					floorItemService.save(item);
				}
			}
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("创建成功"));
			return "redirect:/manage/floor/pcFloor/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑页面
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.GET)
	public String setUpdateForm(Model model,@PathVariable("id") Long id){
		try{
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			List<CategoryVO> voList = categoryService.getCategoryByStatusAndCorpId(StatusEnum.NORMAL.getValue(), corpid);
			model.addAttribute("voList", voList);
			Map<String,Object> map = new  HashMap<String, Object>();
			String floorUrl1 = floorService.getFloorUrl();
			model.addAttribute("floorUrl1", floorUrl1);
			/**把所有的分类转成json字符串*/
			map.put("volist", voList);
			JSONObject.fromObject(map).toString();
			model.addAttribute("voListJson", JSONObject.fromObject(map).toString());
			/**查询所有的商品*/
			Map<String,Object> goodsmap = new  HashMap<String, Object>();
			List<FloorGoodsVO> goodsList = goodsService.getGoodsAllForFloor(GoodsStatusEnum.UP.getValue());
			goodsmap.put("goodsList", goodsList);
			JSONObject.fromObject(goodsmap).toString();
			model.addAttribute("goodsList",goodsList);
			model.addAttribute("goodsvoList", JSONObject.fromObject(goodsmap).toString());
			PcFloor pcFloor = pcFloorService.get(id);
			model.addAttribute("pcFloor", pcFloor);
			model.addAttribute("index", pcFloor.getPcfloorList().size());
			return "floor/pcFloor/update";
		}catch(Exception e){
			logger.error("编辑页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 修改信息
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.POST)
	public String update(@PathVariable("id") Long id,PcFloor pcFloor,RedirectAttributes redirectAttributes){
		try{
			PcFloor s_floor=pcFloorService.get(pcFloor.getId());
			floorItemService.delete(s_floor.getPcfloorList());
			User user = ShiroUser.getInstance().getUser();
			List<PcFloorItem> itemList = pcFloor.getPcfloorList();
			if(itemList.size()>0){
				for (PcFloorItem item : itemList) {
					item.setCreateTime(new Date());
					item.setCreator(user.getUsername());
					item.setFloor(s_floor);
					item.setStatus(StatusEnum.NORMAL.getValue());
					floorItemService.save(item);
				}
			}
			pcFloorService.save(pcFloor);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("编辑成功"));
			return "redirect:/manage/floor/pcFloor/list";
		}catch(Exception e){
			logger.error("编辑错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 删除（逻辑删除）
	 */
	@RequestMapping(value="/delete/{id}",method = RequestMethod.GET)
	public String delete(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			pcFloorService.deleteLogical(id);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("删除成功"));
			return "redirect:/manage/floor/pcFloor/list";
		}catch(Exception e){
			logger.error("删除错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 停用
	 */
	@RequestMapping(value="/disable/{id}",method = RequestMethod.GET)
	public String disable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			pcFloorService.updateStatus(id, StatusEnum.STOP.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("停用成功"));
			return "redirect:/manage/floor/pcFloor/list";
		}catch(Exception e){
			logger.error("停用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 启用
	 */
	@RequestMapping(value="/enable/{id}",method = RequestMethod.GET)
	public String enable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			pcFloorService.updateStatus(id, StatusEnum.NORMAL.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("启用成功"));
			return "redirect:/manage/floor/pcFloor/list";
		}catch(Exception e){
			logger.error("启用错误,id="+id,e);
			return "system/500";
		}
	}
	
	@SuppressWarnings("finally")
	@RequestMapping(value="/updatesort",method = RequestMethod.POST)
	@ResponseBody
	public ResultObject updatesort(RedirectAttributes redirectAttributes,HttpServletRequest request){
		ResultObject result = null;
		try{
			//得到参数
			Long id =Long.valueOf(request.getParameter("id"));
			int sortno = Integer.valueOf(request.getParameter("sortno"));
			//PcFloor pcFloor = pcFloorService.get(id);
			//List<SearchFilter> filterList = new ArrayList<SearchFilter>();
			/*if(cate.getLevel()==2){
				SearchFilter filter = new SearchFilter("parent_id", Operator.EQ,cate.getParent().getId());
				filterList.add(filter);
			}*/
			//SearchFilter filter1 = new SearchFilter("level", Operator.EQ,cate.getLevel());
			//filterList.add(filter1);
			int update= pcFloorService.updateSortNo(Integer.valueOf(sortno), PcFloor.class, id);
			if(update>=0){
				//保存当前修改的排序
				result= new ResultObject("500", "修改成功", null);
			}else{
				result= new ResultObject("300", "修改失败", null);
			}
		}catch(Exception e){
			result = new ResultObject("100", "修改排序出错", null);
		}finally{
			return result;
		}
	}
	
	
	@RequestMapping(value="/test")
	@ResponseBody
	public ResultObject test(){
			return new ResultObject("500", "dd", "策数据哦");
	}
}